package com.hsurosy.hsuchain.nft.file;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;

/**
 * Oss 服务实现类
 *
 * @Author Hsu琛君珩
 * @Date 2024-10-05 4:28
 * @Description
 * @Version: v1.0.0
 */
@Slf4j
@Data
public class OssServiceImpl implements FileService {

    /**
     * Bucket 名称
     */
    private String bucket;

    /**
     * OSS 端点（Endpoint）
     */
    private String endPoint;

    /**
     * 阿里云访问密钥 ID
     */
    private String accessKey;

    /**
     * 阿里云访问密钥 Secret
     */
    private String accessSecret;

    /**
     * 文件上传
     *
     * 上传文件流至指定的 OSS 存储路径
     *
     * @param path 上传到 OSS 的目标路径
     * @param fileStream 文件输入流
     * @return 返回是否上传成功，成功为 true，失败为 false
     */
    @Override
    public boolean upload(String path, InputStream fileStream) {
        // 设置 OSS 端点和访问凭证
        String endpoint = endPoint;
        String accessKeyId = accessKey;
        String accessKeySecret = accessSecret;
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);

        // 设置 Bucket 名称
        String bucketName = bucket;
        // 设置上传的目标对象路径
        String objectName = path;

        // 创建 OSS 客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        boolean uploadRes = false;

        try {
            // 创建 PutObjectRequest 对象，将文件流上传到指定的路径
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, fileStream);

            // 执行上传操作
            PutObjectResult result = ossClient.putObject(putObjectRequest);

            // 检查请求是否成功
            if (StringUtils.isNotBlank(result.getRequestId())) {
                uploadRes = true;  // 上传成功
            }
        } catch (Exception e) {
            // 捕获并记录上传过程中出现的异常
            log.error("OssUtil upload error, path=" + path, e);
        } finally {
            // 关闭 OSS 客户端
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return uploadRes;  // 返回上传结果
    }
}
